#include "taskQueue.h"
#include "threadPool.h"

//父子进程间管道
int exit_pipe[2];

void handler(int signum)
{
    printf("sig %d is comming!\n", signum);
    write(exit_pipe[1],"1",1);
}

int main(int argc,char *argv[])
{
    // ./server ../conf/server.conf
    ARGS_CHECK(argc,2);
    int worker_num;
    char port[256];
    char ip[256];

    //配置文件写入
    FILE* fp = fopen(argv[1],"r");
    ERROR_CHECK(fp,NULL,"fopen");
    //记得调三次fscanf
    //fscanf(fp,"%s %s %d",ip,port,&worker_num);
    fscanf(fp,"%s\n",ip);
    fscanf(fp,"%s\n",port);
    fscanf(fp,"%d\n",&worker_num);
    //printf("%s %d %d\n",ip,atoi(port),worker_num);

    pipe(exit_pipe);
    if(fork() != 0)
    {
        //父进程关闭读端，注册信号，往管道写内容
        close(exit_pipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        exit(0);
    }

    //子进程作为线程池
    close(exit_pipe[1]);
    threadPool_t thread_pool;
    order_t order;
    initThreadPool(&thread_pool,worker_num); //初始化数据结构
    makeWorker(&thread_pool);

    //初始化TCP连接
    int sockfd;
    tcpInit(ip,port,&sockfd);

    //printf("tcpInit over\n");
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exit_pipe[0]);
    struct epoll_event readySet[10];
    //printf("readySet over\n");
    while(1)
    {
        int ready_num = epoll_wait(epfd,readySet,10,-1);
        //printf("epoll_wait over\n");
        for(int i = 0; i < ready_num; ++i)
        {
            if(readySet[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);

                // 主线通知子线程
                pthread_mutex_lock(&thread_pool.task_queue.mutex);
                enqueue(&thread_pool.task_queue,netfd);
                printf("main send a new task!\n");
                pthread_cond_broadcast(&thread_pool.task_queue.cond);
                pthread_mutex_unlock(&thread_pool.task_queue.mutex);
            }
            else if(readySet[i].data.fd == exit_pipe[0])
            {
                printf("threadPool is going to exit!\n");
                pthread_mutex_lock(&thread_pool.task_queue.mutex);
                thread_pool.exit_flag = 1;//说明退出标志位为1
                pthread_cond_broadcast(&thread_pool.task_queue.cond);
                pthread_mutex_unlock(&thread_pool.task_queue.mutex);

                for(int j = 0; j < worker_num; ++j)
                {
                    pthread_join(thread_pool.tid_arr[j],NULL);
                }
                printf("done\n");
                pthread_exit(NULL);
            }
        }
    }
    return 0;
}

